const express = require('express')
const path = require("path")
const fs = require('fs')
const multiparty = require('multiparty')
const titleModel = require('../Model/titleModel')
const materiaModel = require('../Model/materiaModel')
const router = express.Router()

//获取数据
router.post('/getTitle', async (req, res, next) => {
    const data = await titleModel.find().limit(10)
    const datalenth = await titleModel.find()
    res.json({ code: '200', data, msg: datalenth.length })
})
//添加数据
router.post('/addTitle', (req, res, next) => {
    const form = new multiparty.Form({ uploadDir: 'public/title' })
    form.parse(req, async (err, fields, files) => {
        if (err) return res.json({ code: '404', msg: '文件上传失败' })
            let filePath = files.img[0].path;
            let updatedPath = filePath.replace('public//', '');
        titleModel.create({
            title: fields.myData[0],
            Url: path.resolve(__dirname, '../' + updatedPath),
            domainUrl: 'http://101.32.169.227:3000' + files.img[0].path
        })

        if (fields.page[0] <= 1) {
            i = 0
        } else {
            i = (fields.page[0] - 1) * 10 - 1
        }
        const datalenth = await titleModel.find()
        const data = await titleModel.find().skip(i).limit(10)
        res.json({ code: '200', data, msg: datalenth.length })
    })
})
//切换页面数据
router.post('/pageTitle', async (req, res, next) => {
    const { page } = req.body
    const data = await titleModel.find().skip(page === 1 ? 0 : (page - 1) * 10).limit(10)
    res.json({ code: '200', data })
})
//删除标题数据
router.post('/deleteTitle', async (req, res, next) => {
    const { _id, page, oldName } = req.body
    if (page <= 1) {
        i = 0
    } else {
        i = (page - 1) * 10 - 1
    }
    const deletedata = await titleModel.findOne({ _id })
    const deletemateriaModel = await materiaModel.find({ selectData: oldName })
    try {
        fs.unlinkSync(deletedata.Url)
        deletemateriaModel.forEach(item => {
            fs.unlinkSync(item.Url)
            fs.unlinkSync(item.imgUrl)
        })
    } catch (err) {
        return res.json({ code: '404', msg: '删除失败' })
    }
    await materiaModel.deleteMany({ selectData: oldName })
    await titleModel.deleteOne({ _id })
    const data = await titleModel.find().skip(i).limit(10)
    const datalenth = await titleModel.find()
    res.json({ code: '200', data, msg: datalenth.length })
})

//修改标题数据
router.post('/upTitle', async (req, res, next) => {
    const { name, page, _id, oldName } = req.body

    const isTrue = await titleModel.findOne({ title: name })
    if (isTrue) return res.json({ code: '304', msg: '数据重复' })
    if (name === '') return res.json({ code: '404', msg: '数据缺失' })
    if (page <= 1) {
        i = 0
    } else {
        i = (page - 1) * 10 - 1
    }
    console.log(i);
    await titleModel.updateOne({ _id }, { title: name })
    await materiaModel.updateMany({ selectData: oldName }, { selectData: name })
    const data = await titleModel.find().skip(i).limit(10)
    res.json({ code: '200', data })
})
//获取所有数据
router.post('/getTitleM', async (req, res, next) => {
    const data = await titleModel.find()
    res.json({ code: '200', data })
})
//获取所有6个分类
router.post('/getAggregateTitle', async (req, res, next) => {
    const data = await materiaModel.aggregate([
        { $sample: { size: 6 } }
    ]);
    res.json({ code: '200', data })
})


module.exports = router